package cn.ddiancan.dm.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service
public class ThreadPoolMonitor {
    @Autowired
    @Qualifier("ddcDataBackup")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0/5 * * * * *")
    public void monitor() {
        ThreadPoolExecutor threadPoolExecutor = threadPoolTaskExecutor.getThreadPoolExecutor();
        if (!threadPoolExecutor.isTerminated()) {
            log.info("线程池[ddcDataBackup]当前线程数：{}，队列任务数：{},已完成任务数：{}", threadPoolTaskExecutor.getActiveCount(), threadPoolTaskExecutor.getThreadPoolExecutor().getQueue().size(), threadPoolTaskExecutor.getThreadPoolExecutor().getCompletedTaskCount());
            if (threadPoolExecutor.getActiveCount() > 0) {
                ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
                ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds());
                for (ThreadInfo threadInfo : threadInfos) {
                    if (threadInfo.getThreadName().contains("ddcDataBackup")) {
                        log.info("迁移线程：[{}] ,线程状态：{}", threadInfo.getThreadName(), threadInfo.getThreadState());
                    }
                }
            }else{
                List<String> keysToDelete = new ArrayList<>();
                // 扫描匹配特定模式的键
                stringRedisTemplate.execute((RedisCallback<Object>) (connection) -> {
                    Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match("special_data_backup*").count(1000).build());
                    while (cursor.hasNext()) {
                        keysToDelete.add(new String(cursor.next()));
                    }
                    return null;
                });

                // 删除找到的键
                if (!keysToDelete.isEmpty()) {
                    stringRedisTemplate.delete(keysToDelete);
                }
            }
        }
    }
}
